/* eslint-disable @typescript-eslint/no-explicit-any */
import { Controller } from 'egg';


export default class PassportController extends Controller {

  /**
   * 登录验证
   */
  async login() {
    const {
      body: { username, password },
    } = this.ctx.validateReq('passport.login');

    const data = {
      account: username,
      password: this.ctx.helper.md5(
        `${this.ctx.app.config.saltPassword}${password}`,
      ),
    };

    const userDoc = await this.ctx.model.AuthUser.findOne({
      where: {
        username,
      }
    });
    // 用户名错误
    if (!userDoc) return this.ctx.failure({ code: 10003 });

    const Verify = await this.service.passport.accountVerify(
      data.account,
      data.password,
    );

    if (Verify.code) {
      return this.ctx.failure(Verify);
    }

    this.ctx.session.userId = userDoc.id;
    let shop_id
    if (userDoc.type === 1) {
      const { shops } = await this.ctx.model.AuthUser.findOne({
        where: {
          id: userDoc.id,
        },
        include: {
          model: this.ctx.model.Shop,
        },
      });
      console.log(shops);
      if (shops.length) {
        // this.ctx.session.shopId = shops[0].id;
        shop_id = shops[0].id
      }
    }

    console.log(shop_id)
    const token = this.app.jwt.sign({ id: userDoc.id, username: userDoc.username, shop_id }, this.config.jwt.secret);

    return this.ctx.success({
      data: {
        id: userDoc.id,
        userName: userDoc.username,
        token
      },
    });
  }

  /**
   * 退出登录
   */
  async logout() {
    this.ctx.state.user = null;
    this.ctx.success();
    // this.ctx.session = null;
  }
}
